package com.ogilvy.cms.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.ogilvy.cms.bean.CmsDictionary;
import com.ogilvy.cms.bean.CmsLog;
import com.ogilvy.cms.bean.CmsUser;
import com.ogilvy.cms.util.ServiceDispatcher;
import com.ogilvy.common.JSONBean;
import com.ogilvy.common.MetaData;
import com.ogilvy.common.UtilTools;
import com.ogilvy.frame.util.CmsConstants;

@SuppressWarnings("serial")
@Scope("prototype")
@Controller("cms.action.CmsDictionaryAction")
public class CmsDictionaryAction extends AdminAction {
	@Autowired
	protected ServiceDispatcher serviceDispatcher;
	private String rows;//前台以JSON的形式传递数据
	private int start;//分页开始
	private int limit;//每页显示量
	private CmsDictionary cmsdictionary = new CmsDictionary();
	List<CmsDictionary> datalist;
	//转到页面中
    public String index()
    {
    	return "dictionary";
    }
	
	/** 查询 */
	public void query(){
		//设置页面编码
		ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
		String parentId = ServletActionContext.getRequest().getParameter("parentId");
		if(!"".equals(parentId) && null != parentId)
		{
			cmsdictionary.setParentCmdId(Integer.parseInt(parentId));
		}
		else
		{
			cmsdictionary.setParentCmdId(0);
		}
		//根据查询条件，实现模糊查询
		if(rows==null){
			datalist = serviceDispatcher.getCmsDictionaryService().query(cmsdictionary);
		}else
		{
			net.sf.json.JSONObject js = net.sf.json.JSONObject.fromObject(rows);
			Map<String,String> screenMap = new HashMap<String, String>();
			screenMap.put("cmdName",js.getString("cmdName"));
			screenMap.put("parentId",cmsdictionary.getParentCmdId()+"");
//			screenMap.put("startTime",js.getString("startTime"));
//			screenMap.put("endTime",js.getString("endTime"));
			datalist = serviceDispatcher.getCmsDictionaryService().queryByScreen(screenMap);
		}
//		for(int i=0;i<datalist.size();i++)
//		{
//			CmsDictionary dto = datalist.get(i);
//			String id = dto.getCmdId()+"";
//			
//		}
		//datalist = serviceDispatcher.getCmsDictionaryService().query(cmsdictionary);
		//采用集合分页
		limit = datalist.size() > (start+limit)?(start+limit):(datalist.size()-start);
		List pageList = UtilTools.queryForPage(start, limit, datalist);
		JSONBean jbean = new JSONBean();
		MetaData md = new MetaData();

		md.setIdProperty("cmdId");//关联将要显示列表对应的数据字典bean实体的主键ID
		md.reflectFields("com.ogilvy.cms.bean.CmsDictionary");//关联将要显示列表对应的bean实体
		jbean.setMetaData(md);
		jbean.setRows(pageList);
		jbean.setSuccess(true);
		jbean.setTotal(datalist.size());	//此处是datalist

		//String jsonString = UtilTools.encodeObject2Json(jbean);
		String jsonString = UtilTools.encodeObject2Json(jbean,"MM/dd/yyyy HH:mm:ss");
		
		
		
		
		PrintWriter out;
		try {
			out = ServletActionContext.getResponse().getWriter();
			out.print(jsonString);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//return "query";
	}
	
	/** 添加 */
	public void add(){
		net.sf.json.JSONObject js = net.sf.json.JSONObject.fromObject(rows);
		Integer parentCmdId = js.getInt("parentCmdId");		//父字典
		String cmdName = js.getString("cmdName");			//名称
		String cmdValue = js.getString("cmdValue");			//数值
		String cmdDesc = js.getString("cmdDesc");			//说明
		Integer cmdOrderVal = js.getInt("cmdOrderVal");		//排序值
		String cmdValue2 = js.getString("cmdValue2");		//值2
		String cmdValue3 = js.getString("cmdValue3");		//值3
		Integer cmdPubStatus = js.getInt("cmdPubStatus");	//状态
		
		cmsdictionary.setParentCmdId(Integer.valueOf(parentCmdId));
		cmsdictionary.setCmdName(cmdName);
		cmsdictionary.setCmdValue(cmdValue);
		cmsdictionary.setCmdDesc(cmdDesc);
		cmsdictionary.setCmdOrderVal(Integer.valueOf(cmdOrderVal));
		cmsdictionary.setCmdValue2(cmdValue2);
		cmsdictionary.setCmdValue3(cmdValue3);
		cmsdictionary.setCmdPubStatus(Integer.valueOf(cmdPubStatus));
		//添加人  session  获取
		CmsUser cmsuser = (CmsUser)ServletActionContext.getRequest().getSession().getAttribute(CmsConstants.ADMIN_USER);
		String	cmdAdduser = cmsuser.getCmuName();
		cmsdictionary.setCmdAdduser(cmdAdduser);			//将当前用户添加到cmsdictionary对象中
		//添加时间
//		Date getDate = new Date();
//		Date cmdAddtime = getDate;	
		Date cmdAddtime = UtilTools.getCurrrentDate1();
		
		cmsdictionary.setCmdAddtime(cmdAddtime);
		
		CmsDictionary cmsDictionary = serviceDispatcher.getCmsDictionaryService().add(cmsdictionary);
		JSONBean bean = new JSONBean();
		bean.setSuccess(true);
		// 需要新建一个具有id的vo返回给前台以便通知前台保存成功，不然前台一直处于编辑状态
		List rows = new ArrayList();
		rows.add(cmsDictionary);
		bean.setRows(rows);
		//String jsonString = UtilTools.encodeObject2Json(bean);
		String jsonString = UtilTools.encodeObject2Json(bean,"MM/dd/yyyy HH:mm:ss");
		
		/**
		 * 系统日志
		 */
        CmsLog  log = UtilTools.buildLog("数据字典管理", CmsLog.Add, "添加日志", cmdAdduser);
        serviceDispatcher.getCmsLogService().add(log);
		
		PrintWriter out;
		try {
			out = ServletActionContext.getResponse().getWriter();
			out.print(jsonString);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		//return "detail";
	}
	
	/** 修改 */
	public void modify(){
		net.sf.json.JSONObject js = net.sf.json.JSONObject.fromObject(rows);
		//需要修改的项
		Integer cmdId = js.getInt("cmdId");
		//父字典不可修改
		String cmdName = js.getString("cmdName");
		String cmdValue = js.getString("cmdValue");
		String cmdDesc = js.getString("cmdDesc");
		Integer cmdOrderVal = js.getInt("cmdOrderVal");
		String cmdValue2 = js.getString("cmdValue2");
		String cmdValue3 = js.getString("cmdValue3");
		Integer cmdPubStatus = js.getInt("cmdPubStatus");
		
		//根据用户选择的数据字典ID，将查询出来.ID为空。先查询出已经存在的属性，然后对需要修改的属性进行修改
		cmsdictionary = serviceDispatcher.getCmsDictionaryService().get(cmdId);
		
		cmsdictionary.setCmdId(cmdId);
		cmsdictionary.setCmdName(cmdName);
		cmsdictionary.setCmdValue(cmdValue);
		cmsdictionary.setCmdDesc(cmdDesc);
		cmsdictionary.setCmdOrderVal(cmdOrderVal);
		cmsdictionary.setCmdValue2(cmdValue2);
		cmsdictionary.setCmdValue3(cmdValue3);
		cmsdictionary.setCmdPubStatus(cmdPubStatus);
		//修改人，从session中获取
		CmsUser  cmsuser = (CmsUser) ServletActionContext.getRequest().getSession().getAttribute(CmsConstants.ADMIN_USER);
		String	cmdLastuser = cmsuser.getCmuName();
		cmsdictionary.setCmdLastuser(cmdLastuser);
		
		//修改时间，重新获取当前系统时间
//		Date getDate = new Date();
//		Date cmdLasttime = getDate;
		Date cmdLasttime = UtilTools.getCurrrentDate1();
		cmsdictionary.setCmdLasttime(cmdLasttime);
		
		
		//执行修改
		serviceDispatcher.getCmsDictionaryService().modify(cmsdictionary);
		JSONBean bean = new JSONBean();
		bean.setSuccess(true);
		//String jsonString = UtilTools.encodeObject2Json(bean);
		String jsonString = UtilTools.encodeObject2Json(bean,"MM/dd/yyyy HH:mm:ss");
		
		/**
		 * 系统日志
		 */
        CmsLog  log = UtilTools.buildLog("数据字典管理", CmsLog.MODIFY, "修改资源管理部分内容", cmdLastuser);
        serviceDispatcher.getCmsLogService().add(log);
        
		PrintWriter out;
		try {
			out = ServletActionContext.getResponse().getWriter();
			out.print(jsonString);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//return "detail";
	}
	
	public CmsDictionary getCmsdictionary() {
		return cmsdictionary;
	}

	public void setCmsdictionary(CmsDictionary cmsdictionary) {
		this.cmsdictionary = cmsdictionary;
	}
	
	private Integer cmdId;
	public Integer getCmdId() {
		return cmdId;
	}

	public void setCmdId(Integer cmdId) {
		this.cmdId = cmdId;
	}

	public List<CmsDictionary> getDatalist() {
		return datalist;
	}


	 /** 删除 */
    public void del(){
    	net.sf.json.JSONArray objArr = net.sf.json.JSONArray.fromObject(rows);
        for(int i=0;i<objArr.size();i++)
        {
        	net.sf.json.JSONObject js = objArr.getJSONObject(i);
        	//将 String 转化为 Integer 删除
        	String cmdid = js.getString("cmdId");
        	Integer cmdId = Integer.valueOf(cmdid);
            serviceDispatcher.getCmsDictionaryService().del(cmdId);
        }
        //获取数据
        StringBuffer jsonString =new StringBuffer();
        jsonString.append("{");
        jsonString.append("success:true,");
        jsonString.append("msg:'删除成功'");
        jsonString.append("}");
        
		/**
		 * 系统日志
		 */
        CmsUser cmsuser = (CmsUser)ServletActionContext.getRequest().getSession().getAttribute(CmsConstants.ADMIN_USER);
        String	cmdAdduser = cmsuser.getCmuName();
        CmsLog  log = UtilTools.buildLog("数据字典管理", CmsLog.DELETE, "删除XXXXXXX", cmdAdduser);
        serviceDispatcher.getCmsLogService().add(log);
        
        
		
        PrintWriter out;
        try {
        	ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
            out = ServletActionContext.getResponse().getWriter();
            out.print(jsonString.toString());
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
	
	
	public String getRows() {
		return rows;
	}

	public void setRows(String rows) {
		this.rows = rows;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}
	
}
